package com.cykj.enterprise.template;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.cykj.common.entity.OrderDO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @BelongsProject: AliPayExample
 * @BelongsPackage: per.czjy.template
 * @Author: 蔡张君逸
 * @CreateTime: 2025-08-09 17:11
 * @Description: TODO
 * @Version: 1.0
 */
@ConfigurationProperties(prefix = "alipay")
@Component
@Data
public class AlipayTemplate {
    ObjectMapper objectMapper=new ObjectMapper();

    // 应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号
    public String appId;
    // 应用私钥，就是工具生成的应用私钥
    public String merchantPrivateKey;
    // 支付宝公钥,对应APPID下的支付宝公钥。
    public String alipayPublicKey;
    // 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息
    public String notifyUrl;
    //同步通知，支付成功，一般跳转到成功页
    public String returnUrl;
    // 签名方式
    private String signType;
    // 字符编码格式
    private String charset;
    //订单超时时间
    private String timeout = "5m";
    // 支付宝网关；https://openapi-sandbox.dl.alipaydev.com/gateway.do
    public String gatewayUrl;

    public String pay(OrderDO orderDO) throws
            AlipayApiException, JsonProcessingException {

        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = new
                DefaultAlipayClient(gatewayUrl, appId, merchantPrivateKey,
                "json", charset, alipayPublicKey, signType);

        //2、创建一个支付请求，并设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setNotifyUrl(notifyUrl);

        String id = orderDO.getOrderNumber();
        Double money =orderDO.getAmount()*orderDO.getBuyDuration();
        String paymentMethod = "支付宝";


        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", id); // 预生成的订单号
        bizContent.set("total_amount", money);
        bizContent.set("subject", "hr会员充值");
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");
        bizContent.set("timeout_express",timeout);
        bizContent.set("passback_params", objectMapper.writeValueAsString(orderDO)); // 传递业务参数

        alipayRequest.setBizContent(bizContent.toString());
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
        System.out.println("支付宝的响应：" + result);
        return result;
    }
}